package org.laobai.shop.admin.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import org.apache.dubbo.config.annotation.DubboReference;
import org.laobai.shop.goods.entity.Sku;
import org.laobai.shop.goods.entity.Spec;
import org.laobai.shop.goods.entity.Spu;
import org.laobai.shop.goods.service.SkuService;
import org.laobai.shop.goods.service.SpecService;
import org.laobai.shop.goods.service.SpuService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@RequestMapping("sku")
@Controller
public class SkuController {
	@DubboReference
	private SpuService spuService;
	@DubboReference
	private SpecService specService;
	@DubboReference
	private SkuService skuService;
	

	@RequestMapping("toAdd")
	public String toAdd(Integer spuId, Model model) {
		Spu spu = spuService.getById(spuId);
		
		List<Spec> specs = specService.getSpecList();
		
		model.addAttribute("spu",spu);
		model.addAttribute("specs",specs);
		return "/sku/add";
	}
	
	@ResponseBody
	@RequestMapping("saveSku")
	public boolean saveSku(Sku sku,MultipartFile file){
		String path = "D://test//imgs";
		File parent = new File(path);
        if (!parent.exists()) {
            parent.mkdirs();
        }
        //根据MultipartFile获取文件原始名
        String originalFilename = file.getOriginalFilename();
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString().replace("-", "") + extName;

        try {
            file.transferTo(new File(path, fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
		
		sku.setImage(fileName);
		return skuService.saveSku(sku);
	}
}
